import { Component } from "react";
import PropTypes from "prop-types";

export default class Vote extends Component{
    static propTypes={//校验title格式
        title:PropTypes.string.isRequired
    }
    static defaultProps={
        title:"vue好学吗？"
    }
    state={
        supNum:6,
        oppNum:3
    }
    computed=()=>{
      let {supNum,oppNum}=this.state;
      let total=supNum+oppNum;
      if(total<=0){
         return "0.00%";
      }
      return (supNum/total*100).toFixed(2)+"%";
    }
    add(type){
        if(type=="sup"){
            this.setState({
                supNum:this.state.supNum+1
            })
        }else if(type=="opp"){
            this.setState({
                oppNum:this.state.oppNum+1
            })
        }
    }
    render(){
        let {title}=this.props;
        let {supNum,oppNum}=this.state;
        return <div>
            <h1>{title}---总人数：{supNum+oppNum}</h1>
            <div>
                <h2>支持人数：{supNum}</h2>
                <h2>反对人数：{oppNum}</h2>
                <h2>支持率：{this.computed()}</h2>
            </div>
            <div>
                <button onClick={this.add.bind(this,"sup")}>支持</button>
                <button onClick={this.add.bind(this,"opp")}>反对</button>
            </div>
        </div>
    }
}